package com.aya.mapper.model;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnvironmentCapable;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.ClassPathResource;

import java.io.IOException;
import java.util.Properties;

public class EnvXmlBeanFactory extends ClassPathXmlApplicationContext implements EnvironmentCapable {
    private static final String LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME = "LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME";

    public EnvXmlBeanFactory(String configLocation) throws BeansException {
        super(configLocation);
    }

    public EnvXmlBeanFactory(ApplicationContext parent) {
        super(parent);
    }

    @Override
    protected ConfigurableEnvironment createEnvironment() {
        ConfigurableEnvironment environment = super.createEnvironment();

        PropertySource<?> localPropertySource =
                new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties("config.properties"));
        environment.getPropertySources().addLast(localPropertySource);

        return environment;
    }

    protected Properties mergeProperties(String locations) {
        Properties result = new Properties();
        try {
            result.load(new ClassPathResource(locations).getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

}
